package com.myres.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.sql.*;
import com.myres.db.ConnectionPool;
import com.myres.util.UIDTool;

public class Order extends BasicObject {
	public static final long serialVersionUID = 78382434124l;
    private Shop shop;
    private int shopId;
	
	private int uid;
	private User user;
	private Integer state;
	private Integer paymentMode;
	private Float payment = -1.0f;
	private String sendToPlace;
	private String sendToWho;
	private String ReceiverPhone;
	private String sender;
	private java.sql.Timestamp deadline;

	private Timestamp orderTime;
	private Timestamp proceedTime;
	private Timestamp setOutTime;
	private Timestamp arriveTime;


	private Integer status;
	private String signature;
	private int bulkId;// seems useless //comment by hikui
    private Bulk bulk;
	
    public static final int STATE_NEW = 0;
	public static final int STATE_ACCEPTED = 1;

	public static final int STATE_SENT = 2;
	public static final int STATE_ARRIVED = 3;
    private String special_want;
	public String getSpecial_want() {
		return special_want;
	}

	private Set<OrderItem> items;
	private Integer LogisticMode;
	private Byte seen;
	
	//sets added by hikui
	private Set<Critic> critics;
	//added end
	
	

	public static Order newInstance() {
		Order order = new Order();
		order.setNO(UIDTool.generateUID());
		return order;
	}
	
	public Set<Critic> getCritics() {
		return critics;
	}

	public void setCritics(Set<Critic> critics) {
		this.critics = critics;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}

	public byte getSeen() {
		return seen;
	}

	public void setSeen(Byte seen) {
		if(seen != null) this.seen = seen;
	}

	

	public int getLogisticMode() {
		return LogisticMode ==null?0:LogisticMode;
	}

	public Set<OrderItem> getItems() {
		if(items==null) items=new HashSet<OrderItem>();
		return items;
	}
	
	public void setItems(Set<OrderItem> items) {
		this.items = items;
	}
	
	public int getUid() {
		return uid;
	}
	
	public void setUid(int uid) {
		this.uid = uid;
	}
	
	public int getState() {
		return status;
	}
	
	public void setState(Integer state) {
		if(state != null )this.status = state;
	}
	
	public int getPaymentMode() {
		return paymentMode;
	}
	
	public void setPaymentMode(Integer paymentMode) {
		if(paymentMode != null)this.paymentMode = paymentMode;
	}
	
	public float getPayment() {
		if(this.payment>=0) return payment;
		this.payment=0.0f;
		if(this.getItems()==null||this.getItems().size()==0) return 0;
		Iterator<OrderItem> ite=this.getItems().iterator();
		while(ite.hasNext()){
			OrderItem item=ite.next();
			payment+=item.getPrice()*item.getAmount();
		}
		return payment;
	}
	
	public void setPayment(Float payment) {
		if(payment != null) this.payment = payment;
	}
	
	public String getSendToPlace() {
		return sendToPlace;
	}
	
	public void setSendToPlace(String sendToPlace) {
		this.sendToPlace = sendToPlace;
	}
	
	public String getSendToWho() {
		return sendToWho;
	}
	
	public void setSendToWho(String sendToWho) {
		this.sendToWho = sendToWho;
	}
	
	public String getReceiverPhone() {
		return ReceiverPhone;
	}
	
	public void setReceiverPhone(String receiverPhone) {
		ReceiverPhone = receiverPhone;
	}
	
	public String getSender() {
		return sender;
	}
	
	public void setSender(String sender) {
		this.sender = sender;
	}
	
	public java.sql.Timestamp getDeadline() {
		return deadline;
	}
	
	public void setDeadline(java.sql.Timestamp deadline) {
		this.deadline = deadline;
	}
	
	public Timestamp getOrderTime() {
		return orderTime;
	}
	
	public void setOrderTime(Timestamp orderTime) {
		this.orderTime = orderTime;
	}
	
	public Timestamp getProceedTime() {
		return proceedTime;
	}
	
	public void setProceedTime(Timestamp proceedTime) {
		this.proceedTime = proceedTime;
	}
	
	public Timestamp getSetOutTime() {
		return setOutTime;
	}
	
	public void setSetOutTime(Timestamp setOutTime) {
		this.setOutTime = setOutTime;
	}
	
	public Timestamp getArriveTime() {
		return arriveTime;
	}
	
	public void setArriveTime(Timestamp arriveTime) {
		this.arriveTime = arriveTime;
	}
	
	public String getSignature() {
		return signature;
	}
	
	public void setSignature(String signature) {
		this.signature = signature;
	}
	
	public void setShop(Shop shop) {
	    this.shop = shop;
	    if(shop != null) this.shopId=shop.getId();
    }
	
	public Shop getShop() {
	    return this.shop;
	}
	public int getShopId() {
		return shopId;
	}

	public void setShopId(int shopId) {
		this.shopId = shopId;
	}

	public User getUser() {
	   return this.user;
	}
	
	public void setUser(User user) {
	   this.user=user;
	   this.uid=user.getId();
	}
	
	public void setBulk(Bulk bulk) {
	   this.bulk =bulk;
	   if(bulk != null) this .bulkId =bulk.getId();
	}
	public void setBulkId(int  bid) {
	   this.bulkId=bid;
	}
	
	public int getBulkId() {
	   return this.bulkId;
	}
	public Bulk getBulk() {
	   return this.bulk;
	}
	
	public static List<Order> populate(ResultSet rs)  throws SQLException{
		List<Order> l=new ArrayList<Order>();
		while(rs.next()){
			Order o=new Order();
			o.setId(rs.getInt(1));
			o.setNO(rs.getString(2));
			o.setUid(rs.getInt(3));
			o.setState(rs.getInt(4));
			o.setPaymentMode(rs.getInt(5));
			o.setPayment(rs.getFloat(6));
			o.setSendToPlace(rs.getString(7));
			o.setSendToWho(rs.getString(8));
			o.setReceiverPhone(rs.getString(9));
			o.setOrderTime(rs.getTimestamp(10));
			o.setDeadline(rs.getTimestamp(11));
			o.setProceedTime(rs.getTimestamp(12));
			o.setSetOutTime(rs.getTimestamp(13));
			o.setArriveTime(rs.getTimestamp(14));
			o.setSignature(rs.getString(15));
			o.setLogisticMode(rs.getInt(16));
			o.setSpecial_want(rs.getString(17));
			o.setBulkId(rs.getInt(18));
			l.add(o);
		}
		return l;
	}

	public void setSpecial_want(String string) {
		// TODO Auto-generated method stub
		this.special_want=string;
	}

	public void setLogisticMode(Integer int1) {
		// TODO Auto-generated method stub
		if(int1 != null)this.LogisticMode=int1;
	}

	public int insertOrUpdate() throws SQLException{
		Connection con=ConnectionPool.getPool().getConnection();
		PreparedStatement pstmt=con.prepareStatement("update res_orders " +
				"set _status=0 , _payment=? ,_deadline=?,_logistic_mode=? , _bulk_id=? where _no=?");
		pstmt.setFloat(1, this.getPayment());
		pstmt.setString(2, this.getNO());
		pstmt.setTimestamp(3, this.deadline);
		pstmt.setInt(4, this.getLogisticMode());
		pstmt.setInt(5, this.getBulkId());
		System.out.print("No:" + this.getNO());
		int result = pstmt.executeUpdate();
		if (result != 1) {
			System.out.println("not exists the order,create it ");

			if(this.getBulkId()!=0){
				pstmt=con.prepareStatement("insert into res_orders(_no,_user_id,_status,_payment,_bulk_id,_shop_id) values(?,?,?,?,?,?)");
			}else{
				pstmt=con.prepareStatement("insert into res_orders(_no,_user_id,_status,_payment,_shop_id) values(?,?,?,?,?)");
			}
			pstmt.setString(1, this.getNO());
			pstmt.setInt(2, this.uid);
			pstmt.setInt(3, 0);
			pstmt.setFloat(4, this.getPayment());

			if(this.getBulkId()!=0) {
				pstmt.setInt(5,this.getBulkId());
				pstmt.setInt(6, this.getShopId());
			}else{
				pstmt.setInt(5, this.getShopId());
			}
			System.out.println("save to db payment="+this.getPayment());
			result=pstmt.executeUpdate();
		}
	    pstmt=con.prepareStatement("select * from res_orders where _no=?");
	    pstmt.setString(1, this.getNO());
	    ResultSet rs=pstmt.executeQuery();
	    int oid= Order.populate(rs).get(0).getId();
	    
	    pstmt=con.prepareStatement("insert into res_order_items(_no,_order_id,_product_id,_amount,_price,_commented,_saved,_name)values(?,?,?,?,?,?,?,?)");
	    for(OrderItem item:this.items){
	    	item.setOid(oid);
	    	pstmt.setString(1,item.getNO());
	    	pstmt.setInt(2, item.getOid());
	    	pstmt.setInt(3, item.getPid());
	    	pstmt.setInt(4,item.getAmount());
	    	pstmt.setFloat(5, item.getPrice());
	    	pstmt.setByte(6, item.getCommented());
	    	pstmt.setByte(7, item.getSaved());
	    	pstmt.setString(8, item.getName());
	    	pstmt.addBatch();
	    }
	    pstmt.executeBatch();
		con.close();

		return result;

	}
	
	public float getValue(){
		if(this.items==null||this.items.size()==0) return 0;
		float p=0.0f;
		for(OrderItem item:items){
		   p+=	item.getAmount()*item.getPrice();
		}
		return p;
	}
	
	public String toString() {


		String ss = this.sendToWho + "(" + this.getValue() + "元,"
				+ this.sendToPlace + "," + this.ReceiverPhone + ")在"
				+ this.deadline + "送到" + "\n";
		for (OrderItem item : items) {
			ss += item.getName() + "(" + item.getPrice() + ")" + " X "
					+ item.getAmount() + "份; \n";
		}
		return ss;
		/*
		 * String s="接收人："+this.sendToWho+";"; s+="地点："+this.sendToPlace+";\n";
		 * s+="送到时间："+this.deadline+";\n"; s+="电话："+this.ReceiverPhone+";";
		 * s+="总额："+this.getValue()+";\n";
		 * //s+="送货方式："+(this.LogisticMode==0?"�೵":"��ʱ")+"\n";
		 * //s+="֧����ʽ:"+(this.paymentMode==0?"����":"�Ѹ�");
		 * 
		 * for(OrderItem item:items){
		 * s+=item.getName()+"("+item.getPrice()+")"+" X "
		 * +item.getAmount()+"份; \n"; } return s;
		 */

	}
}
